#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
腾讯企业邮箱连接调试工具
提供详细的连接调试信息
"""

import imaplib
import ssl
import socket
from datetime import datetime, timedelta
import sys

# 导入邮箱配置
try:
    from email_config import EMAIL_CONFIG
except ImportError:
    print("未找到配置文件 email_config.py，请创建该文件")
    sys.exit(1)

def debug_connection():
    """调试邮箱连接"""
    # 从配置文件获取邮箱信息
    USERNAME = EMAIL_CONFIG.get('username', '')
    PASSWORD = EMAIL_CONFIG.get('password', '')
    IMAP_SERVER = EMAIL_CONFIG.get('imap_server', 'imap.exmail.qq.com')
    IMAP_PORT = EMAIL_CONFIG.get('imap_port', 993)
    
    if not USERNAME or not PASSWORD:
        print("请在 email_config.py 文件中配置用户名和密码")
        sys.exit(1)
    
    print("=" * 60)
    print("腾讯企业邮箱连接调试工具")
    print("=" * 60)
    
    print(f"配置信息:")
    print(f"  用户名: {USERNAME}")
    print(f"  IMAP服务器: {IMAP_SERVER}")
    print(f"  IMAP端口: {IMAP_PORT}")
    print(f"  当前时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print()
    
    try:
        print("1. 测试网络连接...")
        # 测试网络连接
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(10)
        result = sock.connect_ex((IMAP_SERVER, IMAP_PORT))
        sock.close()
        
        if result == 0:
            print("  ✓ 网络连接正常")
        else:
            print(f"  ✗ 网络连接失败 (错误码: {result})")
            print("    可能原因:")
            print("    - 网络连接问题")
            print("    - 防火墙阻止连接")
            print("    - 服务器地址或端口错误")
            return
        
        print("\n2. 测试SSL/TLS连接...")
        # 测试SSL连接
        try:
            context = ssl.create_default_context()
            with socket.create_connection((IMAP_SERVER, IMAP_PORT), timeout=10) as sock:
                with context.wrap_socket(sock, server_hostname=IMAP_SERVER) as ssock:
                    print(f"  ✓ SSL连接成功")
                    print(f"    协议版本: {ssock.version()}")
        except Exception as e:
            print(f"  ✗ SSL连接失败: {e}")
            print("    可能原因:")
            print("    - SSL证书问题")
            print("    - 服务器不支持SSL")
            return
        
        print("\n3. 测试IMAP连接...")
        # 创建SSL连接
        print(f"  正在连接到 {IMAP_SERVER}:{IMAP_PORT}...")
        mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
        print("  ✓ IMAP服务器连接成功")
        
        # 获取服务器能力
        print("\n4. 获取服务器能力信息...")
        try:
            capabilities = mail.capability()
            print(f"  服务器能力: {capabilities}")
        except Exception as e:
            print(f"  获取服务器能力失败: {e}")
        
        # 登录
        print("\n5. 尝试登录...")
        print("  正在登录...")
        result = mail.login(USERNAME, PASSWORD)
        print(f"  登录结果: {result}")
        print("  ✓ 邮箱登录成功")
        
        # 获取邮箱信息
        print("\n6. 获取邮箱信息...")
        try:
            # 选择收件箱
            status, messages = mail.select('INBOX')
            print(f"  选择收件箱状态: {status}")
            if status == 'OK' and messages and len(messages) > 0:
                message_count = messages[0]
                if message_count is not None:
                    if isinstance(message_count, bytes):
                        num_messages = int(message_count.decode('utf-8'))
                    else:
                        num_messages = int(message_count)
                    print(f"  收件箱邮件数量: {num_messages}")
            
            # 获取邮箱文件夹列表
            print("\n7. 获取邮箱文件夹列表...")
            status, folders = mail.list()
            if status == 'OK':
                print(f"  文件夹数量: {len(folders)}")
                print("  前3个文件夹:")
                for i, folder in enumerate(folders[:3]):
                    if isinstance(folder, bytes):
                        print(f"    {folder.decode('utf-8')}")
                    else:
                        print(f"    {folder}")
        except Exception as e:
            print(f"  获取邮箱信息失败: {e}")
        
        # 关闭连接
        print("\n8. 关闭连接...")
        mail.close()
        mail.logout()
        print("  ✓ 邮箱连接已关闭")
        
        print("\n" + "=" * 60)
        print("调试完成！连接测试成功。")
        print("=" * 60)
        
    except imaplib.IMAP4.error as e:
        print(f"\nIMAP错误: {e}")
        print("\n可能的原因:")
        print("1. 用户名或授权码不正确")
        print("2. IMAP服务未开启")
        print("3. 账户被限制登录")
        print("4. 登录频率限制")
        print("\n建议:")
        print("- 检查邮箱用户名和授权码是否正确")
        print("- 确认已在邮箱设置中开启IMAP/SMTP服务")
        print("- 等待一段时间后再试（可能是频率限制）")
        print("- 尝试重新生成授权码")
    except socket.gaierror as e:
        print(f"\n网络错误: {e}")
        print("可能原因:")
        print("1. 网络连接问题")
        print("2. 服务器地址错误")
        print("3. DNS解析问题")
    except ssl.SSLError as e:
        print(f"\nSSL错误: {e}")
        print("可能原因:")
        print("1. SSL证书问题")
        print("2. 服务器SSL配置问题")
    except Exception as e:
        print(f"\n发生未知错误: {e}")
        print("请检查网络连接和服务器地址")

if __name__ == "__main__":
    debug_connection()